package com.bjpowernode.boss.exception.handle;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bjpowernode.boss.enums.RespInfo;
import com.bjpowernode.boss.exception.PowerException;
import com.bjpowernode.boss.mvc.models.response.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler({PowerException.class})
    public AjaxResult doPowerException(PowerException powerException) {

        log.error("PowerBoss项目异常，code:{},原因:{}", powerException.getRespInfo().getCode(),
                                                     powerException.getRespInfo().getMessage());

        return AjaxResult.FAIL(powerException.getRespInfo());

    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public AjaxResult doMethodArgumentNotValidException(MethodArgumentNotValidException exception) {

        List<FieldError> fieldErrors = exception.getFieldErrors();

        JSONArray objects = new JSONArray();

        for (FieldError fieldError : fieldErrors) {
            JSONObject entries = new JSONObject();
            entries.set(fieldError.getField(), fieldError.getDefaultMessage());
            objects.add(entries);
        }

        return AjaxResult.builder()
                         .code(RespInfo.REQUEST_PARAM_ERROR.getCode())
                         .msg(RespInfo.REQUEST_PARAM_ERROR.getMessage())
                         .data(objects)
                         .build();

    }

}
